package org.aeon.utils;

import lombok.extern.slf4j.Slf4j;
import org.aeon.client.context.GlobalContext;
import org.aeon.client.view.components.menuPanel.PopupPrompt;
import org.aeon.message.Message;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: MissingAeon
 * @date: 2024/3/4 10:42
 * @description:
 */
@Slf4j
public class SimpleRequestUtil {
    /**
     * 发送
     *
     * @param context 上下文
     * @param msg     消息
     */
    public static void send(GlobalContext context, Message msg) {
        context.getChannel().writeAndFlush(msg);
    }

    /**
     * 发送并等待
     *
     * @param context 上下文
     * @param msg     消息
     * @param after   成功回调
     */
    public static void sendAndWait(GlobalContext context, Message msg, Runnable after) {
        context.getWaits().put(msg.getUid(), new CountDownLatch(1));
        context.getChannel().writeAndFlush(msg);
        context.getThreadPool().execute(() -> {
            try {
                if (context.getWaits().get(msg.getUid()).await(10, TimeUnit.SECONDS)) {
                    after.run();
                } else PopupPrompt.createPopUp("请求超时");
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    /**
     * 发送并等待成功或超时
     *
     * @param context 上下文
     * @param msg     消息
     * @param after   成功回调
     * @param fail    超时回调
     */
    public static void sendAndWaitOrTimeout(GlobalContext context, Message msg, Runnable after, Runnable fail, int timeoutSeconds) {
        context.getWaits().put(msg.getUid(), new CountDownLatch(1));
        context.getChannel().writeAndFlush(msg);
        context.getThreadPool().execute(() -> {
            try {
                if (context.getWaits().get(msg.getUid()).await(timeoutSeconds, TimeUnit.SECONDS)) {
                    after.run();
                } else {
                    fail.run();
                }
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        });
    }
}
